package com.kokuma.drawsprite.ftp.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.kokuma.drawsprite.common.StaticValue;
import com.kokuma.drawsprite.ftp.models.CfgFtp;
import com.kokuma.drawsprite.ftp.models.CfgFtpPath;
import com.kokuma.drawsprite.ftp.services.interfaces.ICfgFtpPathServices;
import com.kokuma.drawsprite.ftp.services.interfaces.ICfgFtpServices;

//@Component("ftpClientMananger")
public class FtpClientMananger {
	private static final Logger logger = Logger.getLogger(FtpClientMananger.class);
	
	private Map ftpClientPoolMap = new HashMap();
	ICfgFtpPathServices cfgFtpPathServices;
	ICfgFtpServices cfgFtpServices;

	@Autowired
	public FtpClientMananger(ICfgFtpPathServices cfgFtpPathServices,ICfgFtpServices cfgFtpServices) {
		this.cfgFtpPathServices=cfgFtpPathServices;
		this.cfgFtpServices=cfgFtpServices;
		try {
			List<CfgFtpPath> cfgFtpPathList = cfgFtpPathServices.getCfgFtpPath(null);
			if (cfgFtpPathList != null && cfgFtpPathList.size() > 0) {
				for (int i = 0; i < cfgFtpPathList.size(); i++) {
					CfgFtpPath path = cfgFtpPathList.get(i);
					List<CfgFtp> ftpList = cfgFtpServices.getCfgFtp(path.getCfgFtpCode());
					if (ftpList != null && ftpList.size() > 0) {
						FTPClientConfigure ftpConfig = new FTPClientConfigure();
						CfgFtp ftp = ftpList.get(0);
						ftpConfig.setHost(ftp.getFtpHost());
						ftpConfig.setUsername(ftp.getFtpUser());
						ftpConfig.setPassword(ftp.getFtpPwd());
						ftpConfig.setPort(Integer.parseInt(ftp.getFtpPort()));
						ftpConfig.setPassiveMode(StaticValue.CFG_FTP_PASSIVEMODE);
						ftpConfig.setRetryTimes(StaticValue.CFG_FTP_RETRY_TIMES);
						ftpConfig.setEncoding(StaticValue.CFG_FTP_ENCODING);
						FtpClientFactory ftpCF = new FtpClientFactory(ftpConfig);
						FTPClientPool pool = new FTPClientPool(ftpCF);
						ftpClientPoolMap.put(path.getCfgPathCode(), pool);
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("初始化ftp池出错：", e);
		}
	}

	public FTPClientPool getFtpPool(String cfgPathCode){
		if(StringUtils.isEmpty(cfgPathCode)){
			return null;
		}
		return (FTPClientPool) ftpClientPoolMap.get(cfgPathCode);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
